package cn.middle.remote.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public final class ConversionUtil {

	private ConversionUtil() {}
	
	public static byte[] writeStringBytes(String str) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
		DataOutputStream out = new DataOutputStream(bos);
		byte[] data = new byte[0];
		if(str != null && str.trim().length() > 0) {
			data = str.getBytes();
		}
		try {
			out.writeInt(data.length);
			if(data.length  > 0) {
				out.write(data);
			}
			out.flush();
		} catch (IOException e) {
		}
		return bos.toByteArray();
	}
	
	public static byte[] writeObjectBytes(Object obj) {
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream out = new DataOutputStream(bos);
		
		byte[] data = new byte[0];
		try {
			if(obj != null) {
				data = objectBytes(obj);
			}
			out.writeInt(data.length);
			if(data.length != 0) {
				out.write(data);
			}
			out.flush();
		} catch (IOException e) {
			
		}
		return bos.toByteArray();

	}
	
	private static byte[] objectBytes(Object obj) {
		try {
			
			if(obj instanceof byte[]){
				return (byte[])obj;
			}
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(obj);
			oos.flush();
			return bos.toByteArray();
		} catch (IOException e) {
			return new byte[0];
		}
	}
}
